/**
 * @file 列表页
 * @module pages/list
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires libs/router - 路由跳转
 * @requires config/navbar - 导航配置
 * @requires config/topic - 主题配置
 * @requires models/music - 音乐功能
 * @requires models/story - 故事功能
 * @requires models/service - 通用业务
 * @requires libs/tools - 工具方法
 * @requires libs/utils - 工具函数
 * @requires reactivity - 状态管理库
 */
import router from '../../libs/router';
import { list_navbars } from '../../config/navbar';
import { COLLECT_TYPE, OPEARTION_TYPE, TOPIC } from '../../config/topic';
import musicModel from '../../models/music';
import storyModel from '../../models/story';
import serviceModel from '../../models/service';
import tools from '../../libs/tools';
import { throttle } from '../../libs/utils';
import { createPage } from '@minipro/reactivity';

createPage()({
  /**
   * @property {string} type - 主题类型
   */
  $data: (ctx) => {
    const { topic, type } = ctx.$store.state;
    
    return {
      topic,
      type
    }
  },

  /**
   * @property {number} topicId - 主题ID
   * @property {object} navbars - 图标导航配置
   * @property {string} title - 名称
   * @property {string} coverImgUrl - 背景图
   * @property {string} tags - 标签
   * @property {array} lists - 列表
   * @property {boolean} isCollect - 是否收藏
   */
  data: {
    topicId: 0,
    navbars: list_navbars,
    title: '',
    coverImgUrl: '',
    tags: '',
    lists: [],
    isCollect: false
  },

  onLoad (options) {
    const { id } = options;

    this.setData({
      topicId: id
    });

    // 初始化
    this.init();
  },

  /**
   * @description 初始化函数
   * @returns {void}
   */
  init () {
    // 查询收藏状态
    this.getCollectStatus();
    // 查询主题详情
    this.getTopicDetail();
  },

  /**
   * @description 查询收藏状态
   * @returns {void}
   */
  async getCollectStatus () {
    const { topicId } = this.data,
          collectType = COLLECT_TYPE.TOPIC;

    const { result: { data } } = await serviceModel.getCollectStatus(collectType, topicId);

    this.setData({
      ...data
    });
  },

  /**
   * @description 获取主题详情
   * @returns {void}
   */
  getTopicDetail () {
    const { topic, type, topicId } = this.data;

    // 查询收藏状态
    switch (topic) {
      case TOPIC.MUSIC:
        // 获取音乐主题详情
        this.getMusicTopicDetail(topicId);
        break;
      case TOPIC.STORY:
        // 获取故事主题详情
        this.getStoryTopicDetail(type, topicId);
        break;
      default:
        break;
    }
  },

  /**
   * @description 获取音乐主题详情
   * @param {number} id - 主题ID
   * @returns {void}
   */
  async getMusicTopicDetail (id) {
    try {
      tools.showLoading();
      const { result } = await musicModel.getTopicDetail(id);
      tools.hideLoading();
  
      const { code, message, data } = result;
  
      if (code === 0) {
        this.setData({
          ...data
        });
        return;
      }
      
      console.log(code, message);
      router.goBack();
    } catch (error) {
      console.log('timeout.');
      router.goBack();
    }
  },

  /**
   * @description 获取故事主题详情
   * @param {string} topic - 主题类型
   * @param {number | string} id - 主题ID
   * @returns {void} 
   */
  async getStoryTopicDetail (topic, id) {
    try {
      tools.showLoading();
      const { result } = await storyModel.getTopicDetail(topic, id);
      tools.hideLoading();
  
      const { code, message, data } = result;
  
      if (code === 0) {
        this.setData({
          ...data
        });
        return;
      }
      
      console.log(code, message);
      router.goBack();
    } catch (error) {
      console.log('timeout.');
      router.goBack();
    }
  },

  /**
   * @description 导航栏点击事件处理
   * @param {object} e - 事件源
   * @returns {void} 
   */
  onIconBtnClick: throttle(function (e) {
    const { action } = e.currentTarget.dataset;

    switch (action) {
      case 'back':
        router.goBack();
        break;
      case 'collect':
        this.collectTopic();
        break;
      default:
        console.log('no matching entries.');
        break;
    }
  }, 300, false),

  /**
   * @description 收藏主题
   * @returns {void}
   */
  async collectTopic () {
    const { isCollect, topic, type, topicId } = this.data;

    const operation = isCollect ? OPEARTION_TYPE.DELETE : OPEARTION_TYPE.ADD,
          collectType = COLLECT_TYPE.TOPIC;

    const { result: { code, message } } = await serviceModel.collect(collectType, operation, {
      id: topicId,
      topic,
      type
    });

    if (code === 0) {
      this.setData({
        isCollect: !isCollect
      });
      return;
    }
    
    console.log(message);
  },

  /**
   * @description 跳转至播放页
   * @param {object} e - 事件源
   * @returns {void} 
   */
  onMusicClick: throttle(function (e) {
    const { index } = e.currentTarget.dataset,
          playItem = this.data.lists[index];

    // 处理音频格式
    const playParams = this.formatPlayParams(playItem);

    // 提交数据
    this.$store.commit('changeState', {
      playParams
    });
    // 跳转至播放页
    router.navigate(`/pages/play/play`);
  }, 300, false),

  /**
   * @description 跳转至播放页（播放全部）
   * @param {object} e - 事件源
   * @returns {void} 
   */
  onBtnClick: throttle(function () {
    let { lists } = this.data;

    lists = lists.map(item => this.formatPlayParams(item));

    // 提交数据
    this.$store.commit('changeState', {
      playParams: lists[0],
      playList: {
        lists,
        total: lists.length,
        curIdx: 0
      }
    });
    // 跳转至播放页
    router.navigate(`/pages/play/play`);
  }, 300, false),
  
  /**
   * @description 处理音频格式
   * @param {object} playItem - 音频数据
   * @returns {object}
   */
  formatPlayParams (playItem) {
    const { topic, coverImgUrl } = this.data;

    let playParams = {};
    
    switch (topic) {
      case TOPIC.MUSIC:
        const { id, name, author, url } = playItem;

        playParams = {
          id,
          title: name,
          author,
          imgUrl: url
        }
        break;
      case TOPIC.STORY:
        const { id: _id, title, text } = playItem;

        playParams = {
          id: _id,
          title,
          text,
          imgUrl: coverImgUrl
        }
        break;
      default:
        break;
    }

    return playParams;
  }
})